function [yl, yr] = corrected_km(y, w_lower, w_upper)
    % 输入:
    %   y: 规则输出值向量 (可能包含重复值)
    %   w_lower: 下隶属度向量
    %   w_upper: 上隶属度向量
    % 输出:
    %   yl: 左端点 (标量)
    %   yr: 右端点 (标量)
    
    % 步骤1: 合并相同y值的隶属度区间
    [y_unique, ~, ic] = unique(y);
    n = numel(y_unique);
    
    w_lower_merged = zeros(1, n);
    w_upper_merged = zeros(1, n);
    
    for i = 1:n
        idx = (ic == i);
        w_lower_merged(i) = max(w_lower(idx));
        w_upper_merged(i) = min(w_upper(idx));
    end
    
    % 步骤2: 按y值升序排序
    [y_sorted, sort_idx] = sort(y_unique);
    w_lower_sorted = w_lower_merged(sort_idx);
    w_upper_sorted = w_upper_merged(sort_idx);
    
    % 步骤3: 计算左端点 yl
    yl = compute_endpoint(y_sorted, w_lower_sorted, w_upper_sorted, 'left');
    
    % 步骤4: 计算右端点 yr
    yr = compute_endpoint(y_sorted, w_lower_sorted, w_upper_sorted, 'right');
    
    % 确保 yl <= yr
    if yl > yr
        % 使用边界法作为备选
        yl = min(y_sorted);
        yr = max(y_sorted);
    end
end

function endpoint = compute_endpoint(y, w_l, w_u, direction)
    n = numel(y);
    
    % 初始化权重
    if strcmp(direction, 'left')
        weights = w_u;  % 左端点用上界初始化
    else
        weights = w_l;  % 右端点用下界初始化
    end
    
    % 处理零权重特殊情况
    if sum(weights) == 0
        if strcmp(direction, 'left')
            endpoint = min(y);
        else
            endpoint = max(y);
        end
        return;
    end
    
    % 计算初始质心
    yc = sum(y .* weights) / sum(weights);
    
    % 迭代优化
    max_iter = 100;
    tol = 1e-6;
    for iter = 1:max_iter
        if strcmp(direction, 'left')
            % 左端点：找到使y_k <= yc <= y_{k+1}的k
            k = find(y <= yc, 1, 'last');
            if isempty(k) || k == n
                k = n;
            end
            
            % 更新权重
            new_weights = [w_l(1:k), w_u(k+1:end)];
        else
            % 右端点：找到使y_k <= yc <= y_{k+1}的k
            k = find(y >= yc, 1, 'first');
            if isempty(k) || k == 1
                k = 1;
            end
            
            % 更新权重
            new_weights = [w_u(1:k-1), w_l(k:end)];
        end
        
        % 处理零权重
        if sum(new_weights) == 0
            break;
        end
        
        % 计算新质心
        new_yc = sum(y .* new_weights) / sum(new_weights);
        
        % 检查收敛
        if abs(new_yc - yc) < tol
            break;
        end
        
        yc = new_yc;
        weights = new_weights;
    end
    
    endpoint = yc;
end